package life.mahu.community.interceptor;

import life.mahu.community.mapper.AdminMapper;
import life.mahu.community.model.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class AdminInterceptor implements HandlerInterceptor {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Integer isAdmin = (Integer) request.getSession().getAttribute("isAdminUser");

        Admin admin = adminMapper.selectByPrimaryKey(isAdmin);

        if (admin == null || "".equals(admin)) {
            //未登录，返回登陆页面
            request.setAttribute("message", "没有权限请先登陆");
            request.getRequestDispatcher("/admin/login").forward(request, response);
            return false;
        } else {
            //已登陆，放行请求
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }

}
